﻿var loader = Components.classes["@mozilla.org/moz/jssubscript-loader;1"]
  .getService(Components.interfaces.mozIJSSubScriptLoader);
loader.loadSubScript("chrome://remember/content/common.js");

// This adds .indexOf using .prototype.. Usage Array.indexOf("value") returns the ID of the first string with "value" as value
if(![].indexOf) Array.prototype.indexOf = function(needle){ for(var i=0; i<this.length; i++) if(this[i] == needle) return i; return -1 }

//Connect to the database (Located at the bottom of this file)
databaseConnect();

function contextPopupShowing() {
  gContextMenu.showItem("setRememberAnno", !currentlyRemembered());
  gContextMenu.showItem("removeRememberAnno", currentlyRemembered());
}

// This is the main thingie
var rememberExtension = {
  init: function() {
    var menu = document.getElementById("contentAreaContextMenu");
    menu.addEventListener("popupshowing", contextPopupShowing, false);
    
    var appcontent = document.getElementById("appcontent");   // browser
    if(appcontent)
      appcontent.addEventListener("load", this.onPageLoad, true);
    var messagepane = document.getElementById("messagepane"); // mail
    if(messagepane)
      messagepane.addEventListener("load", this.onPageLoad, true);
  },

  onPageLoad: function(aEvent) {
    var doc = aEvent.originalTarget;
    getAllSites();

    if (allSites.indexOf(doc.location.href) != -1) {
      var justnow = Date.now();
      var statement = mDBConn.createStatement("UPDATE sites SET last = ?1, count = (count + 1) WHERE url = ?2");
      statement.bindInt64Parameter(0, justnow);
      statement.bindStringParameter(1, doc.location.href);
      statement.execute();
    }
  }
}

// This is the function for creating a ranking list and displaying it
function doVooDoo() {
  var justnow = Date.now();
  var statement = mDBConn.createStatement("SELECT * FROM sites");
  var theseSites = new Array();
  
  while(statement.executeStep()) {
    var uri = statement.getString(1);
    var title = statement.getString(2);
    var first = statement.getInt64(3);
    var last = statement.getInt64(4);
    var count = statement.getInt64(5);
    
    // Function resides in common.js
    makeTheseSites(uri, title, first, last, count, theseSites);
  }

  // Function resides in common.js
  sortAndDisplay(theseSites);
}

// This is for saving a site to the database through the right click menu!
// Checks if the URL is allready in the database as well, and does not save if it's there!
function rememberSite() {
  getAllSites();
  var current = getBrowser().currentURI.spec;
  if(allSites.indexOf(current) == -1) {
    var justnow = Date.now();
    var statement = mDBConn.createStatement("INSERT INTO sites VALUES (NULL, ?1, ?2, ?3, ?4, 1)");
    statement.bindStringParameter(0, current);
    statement.bindStringParameter(1, content.document.title);
    statement.bindInt64Parameter(2, justnow);
    statement.bindInt64Parameter(3, justnow);
    statement.execute();
  }
}

// This removes a site from the database, based on the URL of the currently active site
function removeReminder() {
  var current = getBrowser().currentURI.spec;
  var statement = mDBConn.createStatement("DELETE FROM sites WHERE url = ?1");
  statement.bindStringParameter(0, current);
  statement.execute();
}

// This is for reading all sites in the database into an Array
function getAllSites() {
  allSites = new Array();
  var statement = mDBConn.createStatement("SELECT * FROM sites");
  while(statement.executeStep()) {
    allSites.push(statement.getString(1));
  }
  return allSites;
}

// Returns true if it allready is marked by this extension
function currentlyRemembered() {
  getAllSites();
  if (allSites.indexOf(getBrowser().currentURI.spec) != -1) {
    return true;
  } else {
    return false;
  }
}

// This is for connecting to the database and creating it if not there
function databaseConnect() {
  var dbfile = Components.classes["@mozilla.org/file/directory_service;1"]
    .getService(Components.interfaces.nsIProperties)
    .get("ProfD", Components.interfaces.nsIFile);

  dbfile.append("remembertosurf.sqlite");

  var storageService = Components.classes["@mozilla.org/storage/service;1"]
    .getService(Components.interfaces.mozIStorageService);

  mDBConn = storageService.openDatabase(dbfile);
  mDBConn.executeSimpleSQL("CREATE TABLE IF NOT EXISTS sites (id INTEGER PRIMARY KEY, url TEXT, first INTEGER, last INTEGER, count INTEGER)");
  // CHECK IF title EXISTS HERE, IF NOT, CREATE IT
  return mDBConn;
}